package jsp.dao;


import jsp.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;


public abstract class BaseDao<T> {

    public int executeUpdate(String sql, Object[] args) throws Exception {
        Connection con = JdbcUtils.getConnection();
        PreparedStatement pre = con.prepareStatement(sql);
        for (int i = 0; i < args.length; i++) {
            pre.setObject(i + 1, args[i]);
        }
        int executeUpdate = pre.executeUpdate();
        JdbcUtils.close(null, pre, con);
        return executeUpdate;
    }

    public List<T> executeQuery(String sql, Object[] args) throws Exception {
        Connection con = JdbcUtils.getConnection();
        PreparedStatement pre = con.prepareStatement(sql);
        List<T> list = new ArrayList<>();
        for (int i = 0; i < args.length; i++) {
            pre.setObject(i + 1, args[i]);
        }
        ResultSet rs = pre.executeQuery();
        while (rs.next()) {
            T obj = rowToObject(rs);
            list.add(obj);
        }
        JdbcUtils.close(rs, pre, con);
        return list;
    }

    public abstract T rowToObject(ResultSet rs) throws Exception;
}
